package 数组.合并区间;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/5/22 22:10
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        int[][] array = {{3,6},{2,8}};
        int[][] merge = merge(array);
        System.out.println(merge.length);
    }

    public static int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<>();
        if (intervals == null || intervals.length == 0) return res.toArray(new int[0][]);
        // 以每组数据的起点来进行排序
        //Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        int i = 0;
        while (i < intervals.length) {
            int left = intervals[i][0];
            int right = intervals[i][1];
            // 当下一组数据的起点，小于等于当前组数据的终点，就应该继续在当前组的终点和下一组的终点中取最大值即可。
            while (i < intervals.length - 1 && intervals[i + 1][0] <= right) {
                i++;
                right = Math.max(right, intervals[i][1]);
            }
            // 将现在的区间放进res里面
            res.add(new int[]{left, right});
            // 接着判断下一个区间
            i++;
        }
        return res.toArray(new int[0][]);
    }

}
